import argparse
import json
import os
from dora import Node
from mofa.kernel.utils.log import write_agent_log
from mofa.kernel.utils.util import load_agent_config, create_agent_output
from mofa.run.run_agent import run_dspy_agent, run_crewai_agent, run_dspy_or_crewai_agent
from mofa.utils.files.read import read_yaml
import pyarrow as pa
import os
from mofa.utils.files.dir import get_relative_path
from mofa.utils.log.agent import record_agent_prompt_log, record_agent_result_log
import tkinter as tk
from tkinter import messagebox, scrolledtext
import re

RUNNER_CI = True if os.getenv("CI") == "true" else False
def show_long_message(title, message):
    #return
    root = tk.Tk()
    root.title(title)
    
    # 创建滚动文本框
    text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=800, height=200)
    text_area.pack(padx=10, pady=10)
    text_area.insert(tk.END, message)
    text_area.config(state=tk.DISABLED)  # 设置为只读
    
    # 创建关闭按钮
    button = tk.Button(root, text="Close", command=root.destroy)
    button.pack(pady=10)
    
    root.mainloop()
def clean_and_parse_json(raw_code):
    try:
        # 去除第一个 `json` 之前的所有字符
        raw_code_cleaned = re.sub(r'^.*?```json\s*', '', raw_code, flags=re.DOTALL).strip()
        # 去除末尾所有的 `}`、`]` 或 `` ` ``
        raw_code_cleaned = re.sub(r'[\}\]\`]+$', '', raw_code_cleaned).strip()
        
        # 尝试解析 JSON 字符串
        return json.loads(raw_code_cleaned)
    except json.JSONDecodeError as e:
        # 处理无效的转义字符
        raw_code_cleaned = raw_code_cleaned.replace('\\"', '"').replace('\\n', '\n').replace('\\', '\\\\')
        try:
            return json.loads(raw_code_cleaned)
        except json.JSONDecodeError as e:
            # 尝试去除所有非 JSON 字符
            raw_code_cleaned = re.sub(r'[^{}[\],:0-9.\-+Eaeflnr-u \n\r\t]', '', raw_code_cleaned)
            try:
                return json.loads(raw_code_cleaned)
            except json.JSONDecodeError as e:
                # 最后尝试去除所有非 ASCII 字符
                raw_code_cleaned = re.sub(r'[^\x00-\x7F]+', '', raw_code_cleaned)
                return json.loads(raw_code_cleaned)
def main():
    inputs = {}
    agent_result = {}
    results = {}
    # Handle dynamic nodes, ask for the name of the node in the dataflow, and the same values as the ENV variables.
    parser = argparse.ArgumentParser(description="Reasoner Agent")

    parser.add_argument(
        "--name",
        type=str,
        required=False,
        help="The name of the node in the dataflow.",
        default="arrow-assert",
    )
    parser.add_argument(
        "--task",
        type=str,
        required=False,
        help="Tasks required for the Reasoner agent.",
        default="Paris Olympics",
    )

    args = parser.parse_args()
    task = os.getenv("TASK", args.task)

    node = Node()  # provide the name to connect to the dataflow if dynamic node

    # assert_data = ast.literal_eval(data)
    raw_code = ""
    user_query = ""
    source_code = ""
    for event in node:
        if event["type"] == "INPUT":
            if event['id'] in ['task']:
                yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs',
                                                target_file_name='code_evaluation_agent.yml')
                inputs = load_agent_config(yaml_file_path)
                raw_code = event["value"][0].as_py()
                user_query = event["value"][1].as_py()
                source_code = event["value"][2].as_py()
                try:
                    match = re.search(r'```json\s*({.*})\s*```', raw_code, re.DOTALL)
                    if match:
                        raw_code_cleaned = match.group(1)
                    else:
                        # 去除第一个 `json` 之前的所有字符
                        raw_code_cleaned = re.sub(r'^.*?```json\s*', '', raw_code, flags=re.DOTALL).strip()
                        # 去除末尾所有的 `}`、`]` 或 `` ` ``
                        raw_code_cleaned = re.sub(r'[\}\]\`]+$', '', raw_code_cleaned).strip()
                        show_long_message("Error", f"raw_code_cleaned: {raw_code_cleaned}")
                        node.send_output("fixing_code", pa.array(["finish code",raw_code_cleaned,source_code]), event['metadata']) 
                        continue
                except (AttributeError, json.JSONDecodeError) as e:
                    show_long_message("Error", f"Error processing fix code result: {e}")
                    node.send_output("fixing_code", pa.array(["finish code",raw_code_cleaned,source_code]), event['metadata']) 
                    continue
                inputs['task'] = f"'code':{raw_code},'user_question':{user_query}"
                show_long_message("Analysis Information", f"Inputs: {inputs}")
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt')
                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                show_long_message("Analysis Information", f"Agent Result: {agent_result}")
                record_agent_result_log(agent_config=inputs,
                                        agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                try:
                    # 去除 Answer: 和 ```json 前缀和后缀
                    agent_result_cleaned = re.search(r'```json\s*({.*})\s*```', agent_result, re.DOTALL).group(1)
                    # 解析 JSON 对象字符串
                    agent_result_json = json.loads(agent_result_cleaned)
                except (AttributeError, json.JSONDecodeError) as e:
                    show_long_message("Error", f"Error processing agent result: {e}")
                    continue
                # 处理 agent_result_json 对象
                if agent_result_json.get('error') == True:
                    node.send_output("fixing_code", pa.array([agent_result, raw_code]), event['metadata']) 
                else:
                    node.send_output("final_code", pa.array([create_agent_output(step_name='code_assistant',
                                                                                 output_data=raw_code,
                                                                                 dataflow_status=os.getenv(
                                                                                     "IS_DATAFLOW_END",
                                                                                     True))]), event['metadata']) 
            elif event['id'] in ['task2']:
                raw_code = event["value"][0].as_py()
                yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs',
                                                target_file_name='code_evaluation_agent.yml')
                inputs = load_agent_config(yaml_file_path)
                inputs['task'] = f"'code':{raw_code},'user_question':{user_query}"
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt')
                show_long_message("Analysis Information", f"Inputs: {raw_code}")
                try:
                    # 去除 Answer: 和 ```json 前缀和后缀
                    raw_code = re.search(r'```json\s*(\[.*\])\s*```', raw_code, re.DOTALL).group(1)
                    # 解析 JSON 字符串
                    parsed_json = json.loads(raw_code)
                except (AttributeError, json.JSONDecodeError) as e:
                    show_long_message("Error", f"Error processing fix code result: {e}")
                    raw_code = re.sub(r'[\}\]\`]+$', '', raw_code).strip()
                    node.send_output("fixing_code", pa.array(["finish code",raw_code,source_code]), event['metadata']) 
                    continue
                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                #show_long_message("Analysis Information", f"Agent Result: {agent_result}")
                record_agent_result_log(agent_config=inputs,
                                        agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                """ try:
                    # 尝试去除 Answer: 和 ```json 前缀和后缀
                    match = re.search(r'```json\s*(\[.*\])\s*```', agent_result, re.DOTALL).group(1)
                    if match:
                        agent_result_cleaned = match.group(1)
                        agent_result_json = json.loads(agent_result_cleaned)
                    else:
                        # 去除第一个 `json` 之前的所有字符
                        agent_result_cleaned = re.sub(r'^.*?```json\s*', '', agent_result, flags=re.DOTALL).strip()
                        # 去除末尾所有的 `}`、`]` 或 `` ` ``
                        agent_result_cleaned = re.sub(r'[\}\]\`]+$', '', agent_result_cleaned).strip()
                        node.send_output("fixing_code", pa.array([agent_result_cleaned, raw_code]), event['metadata']) 
                        continue
                    # 解析 JSON 对象字符串
                except (AttributeError, json.JSONDecodeError) as e:
                    show_long_message("Error", f"Error processing agent result: {e}")
                    continue
                
                # 处理 agent_result_json 对象
                if agent_result_json.get('error') == True:
                    node.send_output("fixing_code", pa.array([agent_result_cleaned, raw_code]), event['metadata']) 
                else: """
                node.send_output("final_code", pa.array([create_agent_output(step_name='code_assistant',
                                                                                 output_data=raw_code,
                                                                                 dataflow_status=os.getenv(
                                                                                     "IS_DATAFLOW_END",
                                                                                     True))]), event['metadata']) 
if __name__ == "__main__":
    main()
#帮我为1.py集成复数乘法